﻿using System;
using System.Threading;
using NLog;
using OBoobsWallpaper.Configuration;

namespace OBoobsWallpaper.Logic
{
    public class RssManagerScheduler
    {
        private readonly IRssManager rssManager;
        private readonly IRssManagerSchedulerConfig config;
        private Timer timer;
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public RssManagerScheduler(IRssManager rssManager, IRssManagerSchedulerConfig config)
        {
            this.rssManager = rssManager;
            this.config = config;
        }

        private void Callback(object state)
        {
            try
            {
                rssManager.Refresh();
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Unhandled exception was caught from RssManagerScheduler Callback", ex);
            }
        }

        public void Start()
        {
            lock(this)
                if(timer == null)
                    timer = new Timer(Callback, null, 0, (int)config.Interval.TotalMilliseconds);
            Logger.Info("RssManagerScheduler started successfully");
        }

        public void Stop()
        {
            lock (this)
                if (timer != null)
                {
                    timer.Dispose();
                    timer = null;
                    Logger.Info("RssManagerScheduler stoped successfully");
                }
        }
    }
}